package dao;

import java.security.MessageDigest;
import java.util.List;
import mappingOfObject.Usuario;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import persistenceObjectHandler.HibernateSessionManager;
/**
 *
 * @author jano
 */
public class DaoUsuario {

    public static Usuario obtenerUsuarioEmail(String email){
        Session session =HibernateSessionManager.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        Criteria criteria=session.createCriteria(Usuario.class);
                criteria.add(Restrictions.eq("email",email));
        return (Usuario) criteria.uniqueResult();   
    }

    public static boolean validar(String email, String pass) throws Exception {
        Session session =HibernateSessionManager.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        Criteria criteria=session.createCriteria(Usuario.class);
                criteria.add(Restrictions.eq("email",email));
                if(criteria.uniqueResult()!=null){
                    Usuario u= (Usuario) criteria.uniqueResult();
                    System.out.println(u.getEmail()+" "+u.getPass());
                    if(u.getPass().compareTo(pass)==0){
                        return true;
                    }
                    else{
                        return false;
                    }
                }
                else{
                    return false;
                }

    }
    public static String md5(String clear) throws Exception {
	    MessageDigest md = MessageDigest.getInstance("MD5");
	    byte[] b = md.digest(clear.getBytes());
	    int size = b.length;
	    StringBuffer h = new StringBuffer(size);
	    //algoritmo y arreglo md5
	        for (int i = 0; i < size; i++) {
	            int u = b[i] & 255;
	                if (u < 16) {
	                    h.append("0" + Integer.toHexString(u));
	                }
	               else {
	                    h.append(Integer.toHexString(u));
	               }
	           }
	      return h.toString();
    }

    public static List<Usuario> listarUsuarioEmpresa(){
        Session session =HibernateSessionManager.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        Criteria criteria=session.createCriteria(Usuario.class);
                criteria.add(Restrictions.eq("visible",true));
                criteria.add(Restrictions.eq("tipo","empresa"));
        return (List<Usuario>) criteria.list();
    }

}
